import json

from db.redis.redis_service import RedisMemory
from common.log import logger


class PlannerMsgBufferUtil:
    msg_buffer_key = "planner:MsgBuffer:"

    def __init__(self):
        self.redis_memory = RedisMemory()

    def push_msg2buffer(self, session_id, msg):
        data = {"msg": msg}
        self.redis_memory.lpush(PlannerMsgBufferUtil.msg_buffer_key + session_id, json.dumps(data, ensure_ascii=False))

    def pop_msg2buffer(self, session_id):
        res = self.redis_memory.rpop(PlannerMsgBufferUtil.msg_buffer_key + session_id)
        return json.loads(res) if res else None

    def get_top_from_buffer(self, session_id):
        res = self.redis_memory.lindex(PlannerMsgBufferUtil.msg_buffer_key + session_id, 0)
        return json.loads(res) if res else None

    def join_msg2buffer(self, msg, session_id):
        buffer = self.pop_msg2buffer(session_id)
        if buffer:
            buffer_msg = buffer.get('msg')
            if buffer_msg:
                msg = buffer_msg + ' ' + msg
                logger.info(f"当前会话:[{session_id}] 缓冲区有消息:{buffer_msg} 合并消息为:{msg}")
        return msg

    def judge_stop_process(self, msg, session_id):
        buffer = self.get_top_from_buffer(session_id)
        logger.info(f"当前会话:[{session_id}] 缓冲区内容: {buffer}, 本次消息: {msg}")
        if buffer:
            buffer_msg = buffer.get('msg')
            if buffer_msg == msg:
                self.pop_msg2buffer(session_id)
                logger.info(f"当前会话:[{session_id}] 缓冲区的线程id和当前线程id一致, 且缓冲区的消息和当前消息一致, 弹出该消息")
                return False
            else:
                logger.info(f"当前会话:[{session_id}] 缓冲区的消息和当前消息不一致, 返回空字符串")
                return True
        else:
            logger.info(f"当前会话:[{session_id}] 缓冲区没有消息, 返回空字符串")
            return True


def merge_msg(buffer_msg, msg):
    buffer_msg_list = buffer_msg.split(',')
    msg_list = msg.split(',')
    # 使用set集合记录已经添加过的子字符串，并按原始顺序合并
    seen = set()
    merged_list = []
    for segment in buffer_msg_list + msg_list:
        if segment not in seen:
            merged_list.append(segment)
            seen.add(segment)
    # 使用逗号连接合并后的片段
    msg = ','.join(merged_list)
    return msg


planner_msg_buffer_util = PlannerMsgBufferUtil()

if __name__ == '__main__':
    msg_buffer_util = PlannerMsgBufferUtil()
    # msg = msg_buffer_util.join_msg2buffer("不是", '123')
    print(msg_buffer_util.get_top_from_buffer("userFZaJYymJxBUMpifgxjIJ:userCbZn5NZsGMlsInm7OOvn"))
